<!DOCTYPE html>
<html>
<head>
    <title>智能接龙分组工具</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <style>
        body { font-family: -apple-system, sans-serif; margin: 0; padding: 15px; background: #f0f2f5; }
        .container { max-width: 600px; margin: 0 auto; }
        textarea {
            width: 100%;
            height: 200px;
            padding: 12px;
            border: 2px solid #07c160;
            border-radius: 12px;
            font-size: 16px;
            margin: 20px 0;
            box-sizing: border-box;
        }
        button {
            background: #07c160;
            color: white;
            border: none;
            padding: 18px;
            width: 100%;
            border-radius: 12px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: opacity 0.3s;
        }
        .result {
            background: white;
            padding: 20px;
            border-radius: 12px;
            margin-top: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .group-box {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin: 15px 0;
        }
        .auto-score { color: #666; font-size: 0.9em; }
    </style>
</head>
<body>
    <div class="container">
        <h2 style="color: #333; text-align: center;">微信接龙智能分组</h2>
        <textarea id="wechatInput" 
                  placeholder="【直接粘贴微信接龙内容】示例：
#任意标题
1. 玩家A 100
2玩家B
3玩家C 105"></textarea>
        <button onclick="processAndGroup()">立即分组</button>
        <div id="result" class="result"></div>
    </div>

    <script>
        // 增强型正则表达式（支持无分数情况）
        const WEIXIN_REGEX = /^(?:\d+[\.、]?)?\s*([^\d\r\n]+?)(?:\s*(\d{2,3}))?\s*$/;

        function processAndGroup() {
            try {
                const input = document.getElementById('wechatInput').value;
                const players = parseWechatData(input);
                const { groupA, groupB, diff, autoCount } = calculateGroups(players);
                showResult(groupA, groupB, diff, autoCount);
                window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
            } catch (error) {
                alert(error.message);
            }
        }

        function parseWechatData(input) {
            const lines = input.split('\n');
            const players = [];
            let total = 0, validCount = 0;

            lines.forEach(line => {
                line = line.trim();
                if (!line || line.startsWith('#')) return;

                const match = line.match(WEIXIN_REGEX);
                if (!match) throw new Error(`格式错误：${line}`);

                const name = match[1].trim();
                let score = match[2] ? parseInt(match[2]) : null;

                // 记录需要自动填充的分数
                if (score !== null) {
                    if (isNaN(score)) throw new Error(`无效分数：${line}`);
                    total += score;
                    validCount++;
                    players.push({ name, score, auto: false });
                } else {
                    players.push({ name, score: 0, auto: true }); // 暂存占位
                }
            });

            if (players.length === 0) throw new Error("没有检测到有效玩家");
            if (validCount === 0) throw new Error("至少需要一个有效分数");

            // 计算并填充自动分数
            const avg = Math.round(total / validCount);
            players.forEach(p => {
                if (p.auto) p.score = avg;
            });

            if (players.length % 2 !== 0) throw new Error("需要双数人数，当前：" + players.length);
            return players;
        }

        function calculateGroups(players) {
            const groupSize = players.length / 2;
            let minDiff = Infinity;
            let candidates = [];
            const total = players.reduce((sum, p) => sum + p.score, 0);

            function backtrack(start, current) {
                if (current.length === groupSize) {
                    const sum = current.reduce((s, i) => s + players[i].score, 0);
                    const diff = Math.abs(total - 2 * sum);
                    
                    if (diff < minDiff) {
                        minDiff = diff;
                        candidates = [[...current]];
                    } else if (diff === minDiff) {
                        candidates.push([...current]);
                    }
                    return;
                }

                for (let i = start; i < players.length; i++) {
                    if (players.length - i < groupSize - current.length) break;
                    current.push(i);
                    backtrack(i + 1, current);
                    current.pop();
                }
            }

            backtrack(0, []);
            
            const selected = candidates[Math.floor(Math.random() * candidates.length)];
            const autoCount = players.filter(p => p.auto).length;
            return {
                groupA: selected.map(i => players[i]),
                groupB: players.filter((_, i) => !selected.includes(i)),
                diff: minDiff,
                autoCount
            };
        }

        function showResult(groupA, groupB, diff, autoCount) {
            const sumA = groupA.reduce((s, p) => s + p.score, 0);
            const sumB = groupB.reduce((s, p) => s + p.score, 0);

            const resultHTML = `
                <div style="color: #07c160; margin-bottom: 20px;">
                    🎉 分组完成 | 差值：${diff}
                    ${autoCount > 0 ? `<div class="auto-score">（自动填充了 ${autoCount} 个缺失分数）</div>` : ''}
                </div>
                
                <div class="group-box">
                    <div style="color: #07c160; margin-bottom: 10px;">
                        第一组 | 总分：${sumA} 
                        <span style="font-size: 0.8em; color: #666;">(${groupA.length}人)</span>
                    </div>
                    ${groupA.map(p => `
                        <div style="padding: 8px 0; border-bottom: 1px solid #eee;">
                            ${p.name} 
                            <span style="float: right; ${p.auto ? 'color: #666;' : ''}">
                                ${p.score}${p.auto ? '＊' : ''}
                            </span>
                        </div>
                    `).join('')}
                </div>

                <div class="group-box">
                    <div style="color: #07c160; margin-bottom: 10px;">
                        第二组 | 总分：${sumB}
                        <span style="font-size: 0.8em; color: #666;">(${groupB.length}人)</span>
                    </div>
                    ${groupB.map(p => `
                        <div style="padding: 8px 0; border-bottom: 1px solid #eee;">
                            ${p.name} 
                            <span style="float: right; ${p.auto ? 'color: #666;' : ''}">
                                ${p.score}${p.auto ? '＊' : ''}
                            </span>
                        </div>
                    `).join('')}
                </div>

                <div style="text-align: center; margin-top: 20px; color: #666;">
                    再次点击按钮可生成不同组合
                    ${autoCount > 0 ? '<div class="auto-score">（＊表示自动填充的分数）</div>' : ''}
                </div>
            `;

            document.getElementById('result').innerHTML = resultHTML;
        }
    </script>
</body>
</html>